import { Injectable } from '@angular/core';
import { alert, confirm, custom } from 'devextreme/ui/dialog';
import { HttpInterceptorService } from '../utils/http-utils.service';
@Injectable()
export class DialogService {
  fileType = {}
  constructor(private http: HttpInterceptorService) { }
  // !Button onClick的返回值为Promise接收值
  custom(message: string, title ='提示', buttons: Button[]): Promise<any>{
    let customBox = custom({
      title,
      message,
      buttons
    });
    return customBox.show();
  }

  /**
   * 文件下载
   * @param url 文件下载地址
   */
  downloadFile(url: string, fileName: string, params) {
    this.http.requestBidExt({
      method: "post",
      responseType: 'blob',
      url: url,
      data: params
    }).then(res => {
      this.download(res, this.getFileTypeByName(fileName), fileName);
    });
  }

  /**
   * 获取文件后缀名
   * @param {string} filename
   * @returns {any}
   */
  private getFileTypeByName(filename: string) {
    let type = filename.substring(filename.indexOf("."), filename.length);
    return this.fileType[type];
  }


   /**
   * 文件下载
   * @param res 返回结果
   * @param fileType 文件类型
   * @param fileName 文件名
   */
  private download(res: Response, fileType: string, fileName: string) {
    var blob = new Blob([res.body], {type: fileType});
    // ======== 20200804 add by lijinfei IE兼容 ============//
    if('download' in document.createElement('a')) { // 非IE下载
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', fileName);
      a.click();
      URL.revokeObjectURL(objectUrl);
      document.body.removeChild(a);
   } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName);
   }
 }


  alert(message: string, title = '提示'): Promise<any>{
    return alert(message, title);
  }
  // !弹出框按钮为 是 否
  isTrueDialog(message: string, title='提示'): Promise<Boolean>{
    return new Promise((resolve, reject)=>{
      let customBox = custom({
        title,
        message,
        buttons: [
          {
            text: "是",
            onClick: (e) => {
                return true;
            }
          },
          {
            text: "否",
            onClick: (e) => {
              return false;
            }
          }
        ]
      });
      customBox.show().then(result => {
        resolve(result);
      })
    });
  }
  // !弹出窗按钮为 确认 取消
  confirm(message: string, title='提示'): Promise<Boolean> {
    return confirm(message, title);
  }
}
interface Button {
  text: string;
  onClick: (event: any) => any;
}
